package com.bawei.module_mall

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.module_mall.databinding.ActivityAddAddressBinding
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.state.ShopState
import com.bawei.module_mall.http.viewModel.ShopViewModel
import com.bawei.module_mall.model.AddAddressModel
import kotlinx.coroutines.launch
import com.bawei.module_mall.http.repository.ShopRepository
import com.bawei.module_mall.model.AddressModelItem
import com.bawei.module_mall.model.CityModelItem
import com.bawei.module_mall.model.HomeModelItem
import com.bawei.module_mall.model.ProvincesModelItem
import com.bawei.module_mall.model.UpdateModel
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView


@Route(path = Router.Ui.ADDADDRESS_ACTIVITY)
class AddAddressActivity : BaseActivity() {

    private val binding by lazy {
        ActivityAddAddressBinding.inflate(layoutInflater)
    }
    private lateinit var viewModel: ShopViewModel

    // 省市区选择缓存
    private var provinceList: List<ProvincesModelItem> = emptyList()
    private var cityList: List<CityModelItem> = emptyList()
    private var districtList: List<HomeModelItem> = emptyList()
    private var selectedProvince: ProvincesModelItem? = null
    private var selectedCity: CityModelItem? = null
    private var selectedDistrict: HomeModelItem? = null
    // 省市区三级联动数据
    private var editAddress: AddressModelItem? = null
    private var optionsProvinces: List<ProvincesModelItem> = emptyList()
    private var optionsCities: MutableList<List<CityModelItem>> = mutableListOf()
    private var optionsDistricts: MutableList<MutableList<List<HomeModelItem>>> = mutableListOf()
    private var pickerView: OptionsPickerView<Any>? = null

    private fun showAddressPicker() {
        if (optionsProvinces.isNotEmpty() && optionsCities.isNotEmpty() && optionsDistricts.isNotEmpty()) {
            showPickerView()
            return
        }
        lifecycleScope.launch {
            // 1. 获取省
            val provinceResp = ShopRepository().api.getAddressProvince()
            optionsProvinces = provinceResp.data ?: emptyList()
            optionsCities.clear()
            optionsDistricts.clear()
            // 2. 对每个省获取市
            for (province in optionsProvinces) {
                val cityResp = ShopRepository().api.getAddressCity(province.provinceCode)
                val cities = cityResp.data ?: emptyList()
                optionsCities.add(cities)
                // 3. 对每个市获取区
                val districtsOfProvince = mutableListOf<List<HomeModelItem>>()
                for (city in cities) {
                    val districtResp = ShopRepository().api.getAddressHome(city.cityCode)
                    val districts = districtResp.data ?: emptyList()
                    districtsOfProvince.add(districts)
                }
                optionsDistricts.add(districtsOfProvince)
            }
            showPickerView()
        }
    }

    private fun showPickerView() {
        if (optionsProvinces.isEmpty() || optionsCities.isEmpty() || optionsDistricts.isEmpty()) {
            Toast.makeText(this, "地区数据加载失败", Toast.LENGTH_SHORT).show()
            return
        }
        val provinceNames = optionsProvinces.map { it.provinceName }
        val cityNames = optionsCities.map { it.map { c -> c.cityName } }
        val districtNames = optionsDistricts.map { provinceDistricts ->
            provinceDistricts.map { cityDistricts -> cityDistricts.map { d -> d.districtName } }
        }

        pickerView = OptionsPickerBuilder(this) { options1, options2, options3, _ ->
            val province = optionsProvinces[options1]
            val city = optionsCities[options1][options2]
            val district = if (optionsDistricts[options1][options2].isNotEmpty())
                optionsDistricts[options1][options2][options3]
            else null
            selectedProvince = province
            selectedCity = city
            selectedDistrict = district
            binding.etArea.text = if (district != null)
                "${province.provinceName} ${city.cityName} ${district.districtName}"
            else
                "${province.provinceName} ${city.cityName}"
        }
            .setTitleText("请选择省/市/区")
            .setCancelText("取消")
            .setSubmitText("确定")
            .build()

        pickerView?.setPicker(provinceNames, cityNames, districtNames)
        pickerView?.show()
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this)[ShopViewModel::class.java]
        viewModel.handleIntent()
        initListener()
        observeViewModel()
        editAddress = intent.getSerializableExtra("address") as? AddressModelItem
        editAddress?.let { fillAddressData(it) }
    }
    private fun fillAddressData(address: AddressModelItem) {
        binding.etName.setText(address.receiverName)
        binding.etPhone.setText(address.receiverPhone)
        binding.etDetail.setText(address.address)
        binding.etPostcode.setText(address.postalCode)
        binding.switchDefault.isChecked = address.isDefault == 1
        // 地区回显
        binding.etArea.text = "${address.provinceName} ${address.cityName} ${address.districtName}"
        // 设置省市区选择状态，用于后续保存
        selectedProvince = ProvincesModelItem(
            areaCode = address.provinceCode,
            createTime = "",
            level = "",
            parentCode = "",
            provinceCode = address.provinceCode,
            provinceName = address.provinceName,
            updateTime = ""
        )
        selectedCity = CityModelItem(
            areaCode = address.cityCode,
            cityCode = address.cityCode,
            cityName = address.cityName,
            createTime = "",
            level = "",
            parentCode = "",
            updateTime = ""
        )
        selectedDistrict = HomeModelItem(
            areaCode = address.districtCode,
            cityCode = address.cityCode,
            createTime = "",
            districtCode = address.districtCode,
            districtName = address.districtName,
            level = "",
            parentCode = "",
            updateTime = "",
            provinceCode = ""
        )
    }
    private fun initListener() {
        // 地区选择
        binding.etArea.setOnClickListener {
            showAddressPicker()
        }
        // 保存按钮
        binding.btnSave.setOnClickListener {
            submitAddress()
        }
        // 返回按钮
        binding.ivBack.setOnClickListener { finish() }
    }

    private fun observeViewModel() {
        lifecycleScope.launch {
            viewModel.state.collect { state ->
                when (state) {
                    is ShopState.Loading -> {
                        // 可加加载中提示
                    }
                    is ShopState.AddAddressSuccess -> {
                        Toast.makeText(this@AddAddressActivity, "添加成功", Toast.LENGTH_SHORT).show()
                        setResult(RESULT_OK)
                        finish()
                    }
                    is ShopState.UpdateAddressSuccess -> {
                        Toast.makeText(this@AddAddressActivity, "更新成功", Toast.LENGTH_SHORT).show()
                        setResult(RESULT_OK)
                        finish()
                    }
                    is ShopState.ProvincesSuccess -> {
                        provinceList = state.data ?: emptyList()
                    }
                    is ShopState.CitySuccess -> {
                        cityList = state.data ?: emptyList()
                    }
                    is ShopState.HomeSuccess -> {
                        districtList = state.data ?: emptyList()
                    }
                    is ShopState.Error -> {
                        Toast.makeText(this@AddAddressActivity, state.error, Toast.LENGTH_SHORT).show()
                    }
                    else -> {}
                }
            }
        }
    }

    private fun submitAddress() {
        val name = binding.etName.text.toString().trim()
        val phone = binding.etPhone.text.toString().trim()
        val detail = binding.etDetail.text.toString().trim()
        val postcode = binding.etPostcode.text.toString().trim()
        val isDefault = binding.switchDefault.isChecked
        val province = selectedProvince
        val city = selectedCity
        val district = selectedDistrict
        if (name.isEmpty() || phone.isEmpty() || detail.isEmpty() || province == null || city == null || district == null) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show()
            return
        }
        lifecycleScope.launch {
            if (editAddress != null) {
                // 编辑模式，使用用户修改后的表单数据
                val updateModel = UpdateModel(
                    id = editAddress!!.id,
                    address = detail, // 使用用户修改的详细地址
                    checked = isDefault,
                    cityCode = city.cityCode, // 使用当前选择的城市
                    cityName = city.cityName,
                    default = isDefault,
                    districtCode = district.districtCode, // 使用当前选择的区
                    districtName = district.districtName,
                    partnerId = "",
                    postalCode = postcode, // 使用用户修改的邮编
                    provinceCode = province.provinceCode, // 使用当前选择的省
                    provinceName = province.provinceName,
                    receiverAddress = detail,
                    receiverName = name, // 使用用户修改的姓名
                    receiverPhone = phone // 使用用户修改的电话
                )
                viewModel.intents.send(ShopIntent.UpdateAddress(updateModel))
            } else {
                // 新增模式
                val model = AddAddressModel(
                    address = detail,
                    checked = isDefault,
                    cityCode = city.cityCode,
                    cityName = city.cityName,
                    default = isDefault,
                    districtCode = district.districtCode,
                    districtName = district.districtName,
                    postalCode = postcode,
                    provinceCode = province.provinceCode,
                    provinceName = province.provinceName,
                    receiverName = name,
                    receiverPhone = phone
                )
                viewModel.intents.send(ShopIntent.AddAddress(model))
            }
        }
    }
}